package org.example.dao;

import org.example.model.Book;
import org.example.model.Users;
import org.example.utils.DBUtil;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

public class BookDao {
    //新增
    //更新
    //查询一条
    //查询所有
    //删除

    //根据书的分类查询分类中所有的书的信息
    public List<Users> selectByBookCategory(String category){
        //校验参数
        if (category == null || category.isEmpty()){
            System.out.println("分类名为空，请重新输入");
            return null;
        }

        //声明对象
        Connection connection = null;
        PreparedStatement statement = null;
        ResultSet resultSet = null;

        try {
            connection = DBUtil.getConnection();
            String sql = "select u.id,u.name,bu.bname,bu.price,bu.category from bu,users u where u.id=bu.uid and bu.category = ?";
            //获取sql预处理对象，并完成占位符的替换
            statement = connection.prepareStatement(sql);
            statement.setString(1,category);
            //执行sql并获取结果集
            resultSet = statement.executeQuery();
            //遍历结果集
            List<Users> list = null;
            while (resultSet.next()){
                //依次获取列的值
                long id = resultSet.getLong("id");
                String name = resultSet.getString("name");
                String bname = resultSet.getString("bname");
                double price = resultSet.getDouble("price");
                String category1 = resultSet.getString("category");

                //创建一个user对象
                Users users = new Users();
                users.setId(id);
                users.setName(name);

                //创建一个book对象
                Book book = new Book();
                book.setbName(bname);
                book.setPrice(price);
                book.setCategory(category1);

                //建立联系
                users.setBook(book);

                //把当前这个对象加入到list中
                if (list == null){
                    list = new ArrayList<>();
                }
                list.add(users);

                return list;
            }
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }finally {
            DBUtil.close(null,statement,connection);
        }


        return null;
    }
}
